package com.quartz.tasks.config;

import com.quartz.tasks.web.entity.QuartzEntity;
import com.quartz.tasks.web.service.TaskService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * 初始化一个测试定时任务
 */
@Component
public class TaskRunner implements ApplicationRunner {
    
	private final static Logger LOGGER = LoggerFactory.getLogger(TaskRunner.class);
	
	@Autowired
    private TaskService jobService;
	@Autowired
    private Scheduler scheduler;
	
    public void run(ApplicationArguments var) throws Exception{
    	/*
    	Long count = jobService.listQuartzEntity(null);
    	if(count==0){
    		LOGGER.info("初始化测试任务");
    		QuartzEntity quartz = new QuartzEntity();
    		quartz.setJobName("test01");
    		quartz.setJobGroup("test");
    		quartz.setDescription("测试任务");
    		quartz.setJobClassName("com.quartz.tasks.job.TestJob");
    		quartz.setCronExpression("0/20 * * * * ?");
   	        Class cls = Class.forName(quartz.getJobClassName()) ;
   	        cls.newInstance();
   	        //构建job信息
   	        JobDetail job = JobBuilder.newJob(cls).withIdentity(quartz.getJobName(),
   	        		quartz.getJobGroup())
   	        		.withDescription(quartz.getDescription()).build();
   	        //添加JobDataMap数据
   	        job.getJobDataMap().put("data", "{username:zhangsan,age:55}");
		   	job.getJobDataMap().put("names", new String[]{"张三","李四"});
   	        // 触发时间点
   	        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartz.getCronExpression());
   	        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger"+quartz.getJobName(), quartz.getJobGroup())
   	                .startNow().withSchedule(cronScheduleBuilder).build();
			trigger.getJobDataMap().put("data", "{username:zhangsan,age:55}");
			trigger.getJobDataMap().put("names", new String[]{"张三","李四"});
   	        //交由Scheduler安排触发
   	        scheduler.scheduleJob(job, trigger);
    	}
    	*/
    }

}